package user.zc.config.system.template;


import user.zc.config.KeyConfig;
import user.zc.config.ValueType;
import user.zc.config.value.Key;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.util.List;

/**
 * @author zhouchuang
 * @date 2023/8/9 17:54
 */
public class TemplateConfig extends KeyConfig {
    protected static final String EXT = ".ftl";
    private String name;

    public String getName() {
        return name;
    }

    public TemplateConfig() throws Exception {
        super(ValueType.Value);
        this.name = this.getClass().getSimpleName();
    }
    public TemplateConfig(String name) throws Exception {
        super(ValueType.Value);
        this.name = name;
        if(name!=null){
            loadConfig(name);
            copyFile(name);
        }
    }

    @Override
    public File getFile(String fileName){
        File file =  new File(System.getProperty("user.home")+File.separator + FOLD+File.separator+"template"+File.separator+fileName+EXT);
        if(!file.getParentFile().exists()){
            file.getParentFile().mkdirs();
        }
        return file;
    }


    @Override
    protected BufferedReader getConfBufferedReader(String fileName)throws Exception{
        //先判断有么有文件，如果没有就从资源里面读取
        File file  = null;
        if((file = getFile(fileName)).exists()){
            return new BufferedReader(new FileReader(file));
        }else{
            //需要把内容都复制到用户文件夹
            return new BufferedReader(new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream(fileName+EXT)));
        }
    }

    //重载方法，对于配置文件来说，没有用户概念，可以共用
    public  void saveOrUpdate( List<Key> collect)throws Exception{
        saveOrUpdate(this.getClass().getSimpleName(),collect);
    }

    @Override
    public void loadConfig(String fileName) throws Exception {
        setData(readEntity(fileName, Key.class));
    }

    @Override
    public void copyFile(String fileName)throws Exception{
        if(!getFile(fileName).exists()){
            saveOrUpdate(fileName,getData());
        }
    }

}
